
require('./common');
var fs = require('fs');

exports.save = function(req, res){
	
	var tmp_path = req.files.displayImage.path;
	var target_path = '';
	if(req.files!="undefined"){
		target_path = './public/images/users/' + insertedID + "." + getFileName(req.files.displayImage.name);
	}
	
	
	
	var insertSQL = "INSERT INTO user (Email, Display_Name, First_Name, Middle_Name, Last_Name, PicPath, Position_ID, City_ID, Department_ID, Department_Company_ID, User_Level_ID )" +
					" VALUES (" + conn.escape(req.body.Email) +"," + conn.escape(req.body.Display_Name) + 
					", " + conn.escape(req.body.First_Name) + ", " + conn.escape(req.body.Middle_Name) + ", " + conn.escape(req.body.Last_Name) +
					"," + conn.escape() + " ,'1','1','1','1','1' ) ";
	
	conn.query(insertSQL, function(err, results, fields){
		if(err) throw err;
		
		var insertedID =  results.insertId;
		
		fs.rename(tmp_path, target_path, function(err) {
			if (err) throw err;
			// delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files
			fs.unlink(tmp_path, function() {
				if (err) throw err;
				res.send('File uploaded to: ' + target_path + ' - ' + req.files.displayImage.size + ' bytes');
			});
		});
		
	});
}


function getFileName(val){
	var fileName = val.split(".");
	return fileName[fileName.length];
	
}
